package apii.servlet.stud;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import apii.servlet.ServletUtils;
import apii.servlet.UserRequesterData;

/**
 * 
 * @author evgeniy
 * 
 *         TODO: hide all servlets from user's vision site (web.xml security
 *         options)
 * 
 *         TODO: join dopost and doget methods for all servlets
 */
public class StudRootServlet extends HttpServlet {

	public static final String STUD_PREFIX = "/stud";
	public static final String ALL_DISCIPLINES = "all_disciplines";
	public static final String ALL_ALERTS = "all_alerts";
	public static final String UPLOAD_ZIP = "upload_zip";

	public static final String DISCIPLINE_ID = "discipline_id";
	public static final String LAB_ID = "lab_id";
	public static final String CODE_ID = "code_id";

	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public StudRootServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doService(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doService(request, response);
	}

	private void doService(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			response.setContentType("text/html; charset=utf-8");
			UserRequesterData urd = ServletUtils.extractRequesterData(request
					.getSession());
			if ((urd.sessionId == null)
					|| (urd.role != UserRequesterData.ROLE_STUD) || !urd.logged) {
				request.getRequestDispatcher("/illegal").forward(request,
						response);
			} else {
				String requestUri = request.getRequestURI();
				String fullPrefix = ServletUtils.PREFIX + STUD_PREFIX;
				if (!requestUri.startsWith(fullPrefix)) {
					throw new Error();
				}
				// System.out.println(requestUri);
				String filteredUri = requestUri.substring(fullPrefix.length());
				// System.out.println(filteredUri);
				if (filteredUri.matches("(/[a-z[0-9[_]]]+)*/?")) {
					if ((filteredUri.length() > 0)
							&& (filteredUri.charAt(0) == '/')) {
						filteredUri = filteredUri.substring(1);
					}
					String[] tokens = filteredUri.split("/");
					if ((tokens.length == 0)
							|| ((tokens.length == 1) && tokens[0].equals(""))) {
						// dispatch to /stud_home
						request.getRequestDispatcher("/stud_home").forward(
								request, response);
					} else {
						// here tokens[0].equals("")
						if (tokens[0].equals(ALL_DISCIPLINES)) {
							if (tokens.length == 1) {
								request.getRequestDispatcher(
										"/stud_all_disciplines").forward(
										request, response);
							} else if (tokens.length == 2) {
								int discId = ServletUtils
										.getDisciplineId(tokens[1]);
								if (discId == ServletUtils.BAD_DISCIPLINE_URL_ELEMENT) {
									request.getRequestDispatcher("/illegal")
											.forward(request, response);
								} else {
									request.setAttribute(DISCIPLINE_ID, discId);
									request.getRequestDispatcher(
											"/stud_view_discipline").forward(
											request, response);
								}
							} else if (tokens.length == 3) {
								int discId = ServletUtils
										.getDisciplineId(tokens[1]);
								int labId = ServletUtils.getLabId(tokens[2]);
								if (discId == ServletUtils.BAD_DISCIPLINE_URL_ELEMENT
										|| labId == ServletUtils.BAD_LAB_URL_ELEMENT) {
									request.getRequestDispatcher("/illegal")
											.forward(request, response);
								} else {
									// TODO: check that lab corresponds the
									// discipline
									request.setAttribute(DISCIPLINE_ID, discId);
									request.setAttribute(LAB_ID, labId);
									request.getRequestDispatcher(
											"/stud_view_lab").forward(request,
											response);
								}
							} else if (tokens.length == 4) {
								int discId = ServletUtils
										.getDisciplineId(tokens[1]);
								int labId = ServletUtils.getLabId(tokens[2]);
								int codeId = ServletUtils.getCodeId(tokens[3]);
								// check if the is an ask to read code of ask to
								// upload code
								if (codeId != ServletUtils.BAD_CODE_URL_ELEMENT
										&& discId != ServletUtils.BAD_DISCIPLINE_URL_ELEMENT
										&& labId != ServletUtils.BAD_LAB_URL_ELEMENT) {
									request.setAttribute(CODE_ID, codeId);
									request.getRequestDispatcher(
											"/stud_view_code").forward(request,
											response);
								} else if (tokens[3].equals(UPLOAD_ZIP)) {
									System.out.println("attributes:");
									Enumeration<String> names = request
											.getAttributeNames();
									while (names.hasMoreElements()) {
										System.out.println(names.nextElement());
									}
									System.out.println("params:");
									Enumeration<String> params = request
											.getParameterNames();
									while (params.hasMoreElements()) {
										System.out
												.println(params.nextElement());
									}
									System.out.println("the url: "
											+ request.getRequestURL());
									System.out
											.println("bundle id param: "
													+ request
															.getParameter(ZipUploadServlet.BUNDLE_ID));

									Object bundleValue = request
											.getParameter(ZipUploadServlet.BUNDLE_ID);
									if (bundleValue != null) {
										request.setAttribute(
												ZipUploadServlet.BUNDLE_ID,
												bundleValue.toString());
									}
									request.setAttribute(DISCIPLINE_ID, discId);
									request.setAttribute(LAB_ID, labId);
									request.getRequestDispatcher(
											"/stud_zip_upload").forward(
											request, response);
								} else {
									request.getRequestDispatcher("/illegal")
											.forward(request, response);
								}

							} else {
								System.out.println("length inrecognized");
								request.getRequestDispatcher("/illegal")
										.forward(request, response);
							}
						} else if (tokens[0].equals(ALL_ALERTS)) {
							request.getRequestDispatcher("/all_alerts")
									.forward(request, response);
						} else {
							request.getRequestDispatcher("/illegal").forward(
									request, response);
						}
					}
				} else {
					request.getRequestDispatcher("/illegal").forward(request,
							response);
				}
			}
		} catch (SQLException ex) {
			request.getRequestDispatcher("/error").forward(request, response);
			ex.printStackTrace();
		}
	}
}
